package cn.iocoder.yudao.module.infra.dal.redis.nacos;

import cn.iocoder.yudao.module.infra.dal.redis.InfraRedisKeyConstants;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Repository
public class NacosLockRedisDAO {

    @Resource
    private RedissonClient redissonClient;

    public <T> T lockGlobal(Callable<T> callable) {
        final String lockKey = InfraRedisKeyConstants.NACOS_LOCK_GLOBAL;
        final RLock lock = redissonClient.getLock(lockKey);
        try {
            final Long timeoutMillis = 1000L * 30;
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            lock.unlock();
        }
    }

}
